package com.hp.bon.sgw.wh.mml.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.bon.sgw.wh.mml.helper.LogMsgHelper;
import com.hp.bon.sgw.wh.mml.helper.LogMsgWriter;
import com.hp.bon.sgw.wh.mml.helper.PropertiesHelper;
import com.hp.bon.sgw.wh.mml.repositories.LogMsgRepository;
import com.hp.bon.sgw.wh.mml.repositories.PropertyRepository;

public class MsgLogServerHandler extends Thread {
	
	private static final Logger logger = LoggerFactory.getLogger(MsgLogServerHandler.class);
	
	private boolean stop = false;
	
	private static MsgLogServerHandler handler = null;
	
	public static void startHandler(){
		if(handler==null){
			handler = new MsgLogServerHandler();			
		}
		if(!PropertyRepository.isLogMsgEnable()){
			logger.info("MsgLogServerHandler NOT Enable.");
		} else if(!isRunningHandler()){
			handler.stop = false;
			handler.start();
		}
	}
	
	public static void stopHandler(){
		handler.stop = true;
	}
	
	public static boolean isRunningHandler(){
		return handler.isAlive();
	}
	
	private MsgLogServerHandler(){
		setDaemon(false);
	}
	
	@Override
	public void run() {
		
		logger.info("MsgLogServerHandler is running...");
		
		LogMsgWriter logMsgWriter = new LogMsgWriter(PropertyRepository.getLogMsgPath());
		logMsgWriter.openLogFile();
		while (true) {
			if(stop){
				break;
			}
			String msgLine = LogMsgRepository.pollLogMsgLine();
			if(msgLine==null){
				try {
					sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				logMsgWriter.writeOneLine(msgLine);
			}			
		}
		logMsgWriter.closeLogFile();
	}
	
	public static void main(String[] args){
		
		PropertiesHelper.loadZBVCProperties();
		
		LogMsgHelper.appendLogMsg("test1");
		LogMsgHelper.appendLogMsg("test2");
		LogMsgHelper.appendLogMsg("test3");
		MsgLogServerHandler.startHandler();
		try {
			Thread.sleep(50000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		MsgLogServerHandler.stopHandler();
		try {
			Thread.sleep(50000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
